import {movieSubjectDetailUsingGET} from '@/services/otherworldly-station-backend/DoubanController';
import {
    addFilmTelevisionUsingPOST,
    deleteFilmTelevisionUsingPOST,
} from '@/services/otherworldly-station-backend/FilmTelevisionController';
import {ProCard} from '@ant-design/pro-components';
import {Badge, Button, Card, Divider, Image, List, message, Modal, Pagination, Spin, Tag} from 'antd';
import React, {CSSProperties, useState} from 'react';
import styles from './CardList.less';

export type Props = {
    records: API.DoubanSearchMovieVO[];
    setDoubanPage: (page: number) => void;
    doubanPage: number;
    doubanPageSize: number;
    recordsCount: number;
    searchKey: string;
    onSearchData: (count: number, start: number, value: string) => Promise<void>;
};

const iconStyles: CSSProperties = {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '18px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};

const DoubanCardList: React.FC<Props> = (props) => {
    const {
        records,
        recordsCount,
        doubanPage,
        doubanPageSize,
        setDoubanPage,
        onSearchData,
        searchKey,
    } = props;
    const [modalOpen, setModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [movieItem, setMovieItem] = useState<API.DoubanSearchMovieVO>({});
    const [isCompleteLoading, setIsCompleteLoading] = useState<boolean>(false);
    const [isWatched, setIsWatched] = useState<boolean>(false);

    // 链接中转，通过其他网站重定向展示图片
    const getImages = (_url: string | undefined) => {
        if (_url !== undefined) {
            let _u = _url.substring(7);
            return 'https://images.weserv.nl/?url=' + _u;
        }
    };

    const addMyFavorite = (watchStatus: number) => {
        setSubmitLoading(true);
        // 加入收藏
        addFilmTelevisionUsingPOST({
            id: movieItem.id,
            name: movieItem.title,
            description: movieItem.summary,
            images: JSON.stringify(movieItem.images),
            type: movieItem.subType,
            releaseDate: movieItem.year,
            tags: JSON.stringify(movieItem.genres),
            score: movieItem.average,
            watchStatus,
        })
            .then((res) => {
                console.log(res);
                if (res.code === 0) {
                    message.success('成功加入影片列表');
                }
            })
            .finally(() => {
                setSubmitLoading(false);
                setModalOpen(false);
            });
    };
    const deleteMyFavorite = (id: number) => {
        setSubmitLoading(true);
        // 取消收藏，删除本地记录
        deleteFilmTelevisionUsingPOST({id})
            .then((res) => {
                if (res.code === 0) {
                    message.warning('影片已从您的影视列表中移除');
                }
            })
            .finally(() => {
                setModalOpen(false);
                setSubmitLoading(false);
            });
    };

    /**
     * 获取影片详情
     * @param id
     */
    const showMovieDetail = (id: number) => {
        setIsWatched(false);
        setIsCompleteLoading(true);
        setMovieItem({});
        // 获取影片详情
        movieSubjectDetailUsingGET({id})
            .then((res) => {
                if (res.code === 0) {
                    let data = res.data as API.DoubanSearchMovieVO;
                    console.log('showMovieDetail：', data);
                    if (data.watchStatus) {
                        // 有值说明已存入影视列表
                        setIsWatched(true);
                    }
                    setMovieItem(data);
                    setIsCompleteLoading(false);
                    setModalOpen(true);
                }
            })
            .finally(() => {
                setIsCompleteLoading(false);
            });
    };

    return (
        records && (
            <>
                <Spin spinning={submitLoading}>
                    <Modal
                        width="500px"
                        centered
                        open={modalOpen}
                        onCancel={() => setModalOpen(false)}
                        footer={
                            isWatched
                                ? [
                                    <Button
                                        key="dislike"
                                        onClick={() => deleteMyFavorite(movieItem.id as number)}
                                    >
                                        不想看
                                    </Button>,
                                ]
                                : [
                                    <Button key="back" onClick={() => setModalOpen(false)}>
                                        取消
                                    </Button>,
                                    <Button
                                        key="watched"
                                        type="default"
                                        style={{backgroundColor: '#ed6d3d', color: '#fff'}}
                                        onClick={() => addMyFavorite(3)}
                                    >
                                        看过
                                    </Button>,
                                    <Button
                                        key="watchings"
                                        type="primary"
                                        style={{backgroundColor: '#ed6d46', color: '#fff'}}
                                        onClick={() => addMyFavorite(2)}
                                    >
                                        在看
                                    </Button>,
                                    <Button
                                        key="wishWatch"
                                        style={{backgroundColor: '#e94829', color: '#fff'}}
                                        onClick={() => addMyFavorite(1)}
                                    >
                                        想看
                                    </Button>,
                                ]
                        }
                    >
                        <ProCard
                            direction="column"
                            ghost
                            gutter={{
                                xs: 1,
                                sm: 1,
                                md: 1,
                                lg: 1,
                                xl: 1,
                                xxl: 2,
                            }}
                            style={{overflow: 'auto', marginTop: '15px'}}
                            className={styles.coverCardList}
                        >
                            <ProCard style={{textAlign: 'center'}}>
                                <Image width={200} src={getImages(movieItem.images?.medium)}/>
                            </ProCard>
                            <ProCard>
                                <h2>
                                    <b>{movieItem.title}</b>
                                </h2>
                                {movieItem.genres
                                    ? movieItem.genres.map((item, index) =>
                                        index < 7 ? (
                                            <Tag
                                                key={item}
                                                bordered={true}
                                                color="#fa5822"
                                                style={{marginBottom: '10px'}}
                                            >
                                                {item}
                                            </Tag>
                                        ) : null,
                                    )
                                    : null}
                                <Divider style={{margin: '0 0 10px 0'}}/>
                                <div style={{height: 'auto'}}>{movieItem.summary}</div>
                            </ProCard>
                        </ProCard>
                    </Modal>
                </Spin>
                <Spin size="large" spinning={isCompleteLoading}>
                    <List<any>
                        className={styles.coverCardList}
                        rowKey="id"
                        grid={{gutter: 24, xxl: 8, xl: 6, lg: 4, md: 4, sm: 2, xs: 1}}
                        dataSource={records}
                        renderItem={(item) => {
                            return (
                                <List.Item>
                                    <Card
                                        className={styles.card}
                                        hoverable
                                        cover={
                                            <img
                                                alt={item.title}
                                                src={getImages(item.images.small)}
                                            />
                                        }
                                        onClick={() => {
                                            showMovieDetail(item.id);
                                        }}
                                    >
                                        <Card.Meta
                                            title={<a>{item.title}</a>}
                                            description={
                                                item.subType && item.subType === 'Movie'
                                                    ? '电影'
                                                    : '电视剧'
                                            }
                                        />
                                        <div className={styles.cardItemContent}>
                                            <span>{item.year ? item.year + ' 年上映' : null}</span>
                                        </div>
                                    </Card>
                                </List.Item>
                            );
                        }}
                    />
                    {doubanPageSize < recordsCount ? (
                        <Pagination
                            style={{textAlign: 'center'}}
                            simple
                            defaultCurrent={doubanPage}
                            defaultPageSize={doubanPageSize}
                            total={recordsCount}
                            onChange={async (page, pageSize) => {
                                await onSearchData(pageSize, (page - 1) * pageSize, searchKey);
                                setDoubanPage(page);
                                window.scrollTo({
                                    top: 0,
                                    behavior: 'smooth',
                                });
                            }}
                        />
                    ) : null}
                </Spin>
            </>
        )
    );
};

export default DoubanCardList;
